<template>
  <n-card>
    <!--职位查询-->
    <n-form inline :model="queryParams" label-placement="left">
      <n-form-item label="部门名称" path="name">
        <n-input v-model:value="queryParams.name" :clearable="true" />
      </n-form-item>
      <n-form-item label="部门状态" path="name">
        <n-select
          v-model:value="queryParams.status"
          style="width: 160px"
          :options="stateTypeList"
          :clearable="true"
        />
      </n-form-item>
      <n-form-item>
        <n-button attr-type="button" @click="reloadTable">查询</n-button>
      </n-form-item>
    </n-form>

    <!--页面表格信息-->
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionTableRef"
      :actionColumn="actionColumn"
      :pagination="false"
      v-model:checked-row-keys="checkedRowKeys"
    >
      <template #tableTitle>
        <n-button type="primary" @click="onOpenAddDept">新增部门</n-button>
      </template>
      <template #toolbar> </template>
    </BasicTable>

    <!--新增或修改职位-->
    <n-modal
      :show-icon="false"
      v-model:show="modelInfo.show"
      preset="dialog"
      :title="modelInfo.info.id ? '修改部门' : '新增部门'"
    >
      <n-form
        :model="modelInfo.info"
        ref="deptFormRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
        :rules="deptFormRules"
      >
        <n-form-item label="上级部门" path="parentId">
          <n-tree-select
            v-model:value="modelInfo.info.parentId"
            :options="deptTree"
            label-field="name"
            key-field="id"
            children-field="children"
          />
        </n-form-item>
        <n-form-item label="部门名称" path="name">
          <n-input placeholder="请输入部门名称" v-model:value="modelInfo.info.name" />
        </n-form-item>
        <n-form-item label="显示排序" path="treeSort">
          <n-input-number
            placeholder="排序"
            v-model:value="modelInfo.info.treeSort"
            :step="1"
            :min="0"
          />
        </n-form-item>
        <n-form-item label="部门状态" path="status">
          <n-radio-group v-model:value="modelInfo.info.status">
            <n-space>
              <n-radio v-for="item in stateTypeList" :key="item.value" :value="item.value">
                {{ item.label }}
              </n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="备注" path="date">
          <n-input type="textarea" v-model:value="modelInfo.info.remark" />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="modelInfo.show = false">取消</n-button>
          <n-button type="info" @click="onAddOrEditDept">确认</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="tsx" setup>
  import { h, ref, reactive } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { useInitDict } from '@/hooks/dictHooks';
  import { NTag, NButton } from 'naive-ui';
  import {
    getDeptTreeApi,
    getTreeByEntityApi,
    addDeptApi,
    modifyDeptApi,
    deleteDeptApi,
  } from '@/api/system/dept';
  import { debounce, deleteNullChildren, structureParams } from '@/utils';

  import { activeColumnHooks } from '@/hooks/activeColumnHooks';
  import { messageHooks } from '@/hooks/baseHooks';

  const { message, IDialog } = messageHooks();
  const actionTableRef = ref();
  const deptFormRef = ref();
  const deptFormRules = reactive({
    parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
    treeSort: [{ required: true, message: '显示排序不能为空', trigger: 'blur', type: 'number' }],
  });
  const deptTree = ref([]);

  let modelInfo = reactive({
    show: false,
    info: {},
  }); //显示新增修改弹窗

  function resetModelInfo() {
    modelInfo.show = false;
    modelInfo.info = {
      id: undefined,
      parentId: '1000000000000000001',
      name: undefined,
      status: 'ENABLE',
      remark: undefined,
      treeSort: undefined,
    };
    onGetDeptTreeData();
  }

  /**
   * 获取部门tree数据
   */
  function onGetDeptTreeData() {
    getDeptTreeApi({}).then((res) => {
      if (res && res.code === 'A00000') {
        deptTree.value = [
          {
            id: '1000000000000000001',
            name: '顶级',
            children: deleteNullChildren(res.data),
          },
        ];
      }
    });
  }

  //初始化数据字典
  const { menuTypeDict, viewTypeDict, yesNoDict, requestTypeDict, stateTypeList } = useInitDict({
    MENU_TYPE: 'menuTypeDict',
    VIEW_TYPE: 'viewTypeDict',
    YES_NO: 'yesNoDict',
    REQUEST_TYPE: 'requestTypeDict',
    STATUS_TYPE: 'stateTypeList',
  });

  //定义查询条件
  const queryParams = reactive({
    name: undefined,
    status: undefined,
  });

  //查询表格数据
  function reloadTable() {
    actionTableRef.value.refresh(true);
  }

  //定义表格多选中项
  const checkedRowKeys = ref([]);

  //表格列配置
  const columns = [
    {
      title: '部门名称',
      key: 'name',
    },
    {
      title: '显示排序',
      key: 'treeSort',
    },
    {
      title: '部门状态',
      key: 'status',
      render(row) {
        return row.status === 'ENABLE' ? (
          <NTag type="success">启用</NTag>
        ) : (
          <NTag type="error">停用</NTag>
        );
      },
    },
    {
      title: '创建时间',
      key: 'createDate',
    },
    {
      title: '备注',
      key: 'remark',
    },
  ];

  //表格操作列配置
  const { actionColumn } = activeColumnHooks(handleDelete, onOpenEditPost);

  //加载表格数据方法
  const loadDataTable = async () => {
    let params = {
      ...queryParams,
    };

    const res = await getTreeByEntityApi(structureParams(params));

    return deleteNullChildren(res.data);
  };

  //点击修改按钮
  function onOpenEditPost(record: Recordable) {
    resetModelInfo();
    modelInfo.info = { ...record };
    modelInfo.show = true;
  }

  //点击删除按钮
  function handleDelete(record: Recordable) {
    IDialog.success('你确定删除当前部门？', () => {
      deleteDeptApi(record).then((res) => {
        if (res && res.code === 'A00000') {
          reloadTable();
          message.success(res.msg);
        } else {
          message.error(res.msg);
        }
      });
    });
  }

  //打开新增部门页面
  function onOpenAddDept() {
    resetModelInfo();
    modelInfo.show = true;
  }

  const onAddOrEditDept = debounce(function () {
    deptFormRef.value.validate((errors) => {
      if (!errors) {
        if (modelInfo.info.id === undefined) {
          // 新增部门
          addDeptApi(modelInfo.info).then((res) => {
            if (res.code === 'A00000') {
              message.success(res.msg);
              modelInfo.show = false;
              reloadTable();
            } else {
              console.log('modify failed');
              message.error(res.msg);
            }
          });
        } else {
          // 修改职位
          modifyDeptApi(modelInfo.info).then((res) => {
            if (res.code === 'A00000') {
              message.success(res.msg);
              modelInfo.show = false;
              reloadTable();
            } else {
              message.error(res.msg);
            }
          });
        }
      }
    });
  });
</script>

<style scoped></style>
